package com.zhongbo.java.websocket.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhongbo.java.websocket.mapper.UserMapper;
import com.zhongbo.java.websocket.model.User;
import com.zhongbo.java.websocket.service.IUserService;
import com.zhongbo.java.websocket.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 说明：
 * 用户服务业务逻辑代码
 *
 * @author 钟波dellNotebook
 * @since 2025年03月18日 星期二 14:09:54
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String add(User user) {
        if (user == null) {
            throw new RuntimeException("用户实体不能为空");
        }
        user.setCreateTime(new Date());
        // 返回插入数据库的数量
        int insert = userMapper.insert(user);
        // 判断插入数量>0,表示插入成功;
        if (insert > 0) {
            // 返回插入的用户id
            return user.getId();
        }
        throw new RuntimeException("新增用户失败");
    }

    @Override
    public int deleteOne(String userId) {
        int delete = userMapper.deleteById(userId);
        // 判断delete数量大于0表示成功
        if (delete > 0) {
            return delete;
        }
        throw new RuntimeException("删除用户失败! id: " + userId);
    }

    @Override
    public User editByUserId(User user) {
        if (user == null) {
            throw new RuntimeException("用户信息为空,更新失败");
        }
        // 调用userMapper的updateById根据用户id来更新用户信息
        int update = userMapper.updateById(user);
        if (update > 0) {
            // 删除成功, 返回更新后的user信息
            return user;
        }
        throw new RuntimeException("更新用户失败");
    }

    @Override
    public User detail(String userId) {
        // 验证用户id不能为空字符串
        if (StrUtil.isBlank(userId)) {
            throw new RuntimeException("用户id不能为空");
        }
        return userMapper.selectById(userId);
    }

    @Override
    public PageVo<User> page(String userName, int pageNumber, int pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 判断包含用户名称查询条件, 将查询条件添加到queryWrapper里
        if (StrUtil.isNotBlank(userName)) {
            // 添加模糊查询用户名条件
            queryWrapper.like("name", userName);
        }
        // 构建分页查询参数
        IPage<User> pageParam = new Page<>(pageNumber, pageSize);
        IPage<User> userIPage = userMapper.selectPage(pageParam, queryWrapper);
        return new PageVo<>(userIPage);
    }

    @Override
    public List<User> listUserByUserIds(List<String> userIdList) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",userIdList);
        return userMapper.selectList(queryWrapper);
    }
}
